package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.service.CompanyInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@RestController
public class CompanyInfoController {

    @Autowired
    private CompanyInfoService companyInfoService;

    @GetMapping("/export/company")
    public void exportCompany(HttpServletResponse response) {
        try {
            companyInfoService.downloadExcel(response);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            response.setStatus(500);
        }
    }

    @PostMapping("/import/company")
    public String importCompany(@RequestParam("file") MultipartFile file) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            return "上传失败，请选择一个文件";
        }
        // 检查文件格式:cite[3]
        String originalFilename = file.getOriginalFilename();
        if (originalFilename != null &&
                (!originalFilename.endsWith(".xls") && !originalFilename.endsWith(".xlsx"))) {
            return "上传失败，仅支持 .xls 或 .xlsx 格式的Excel文件";
        }
        try {
            this.companyInfoService.uploadExcel(file);
        } catch (IOException e) {
            return "文件上传并解析失败！";
        }
        return "文件上传并解析成功！";
    }
}